import QtQuick 2.15
import QtQuick.Controls 2.15
import QtQuick.Layouts 1.15
import Qt.labs.qmlmodels 1.0

MainView {
    id: root
    property string tableName: "weightTable"
    property int verHeaderHeight: 30
    property int verHeaderWidth: 0
    property int horHeaderHeight: 30
    property variant columnWidthArr: [250,250,100,200]
    property string m_startTime:Qt.formatDateTime(new Date(), "yyyy-MM-dd 00:00:00")
    property string m_endTime:Qt.formatDateTime(new Date(), "yyyy-MM-dd 23:59:59")
    property int m_currentPage:0
    property int btnWidth:30
    property int btnHeight:50
    signal signalRefresh
    property int dateType:0
    property int totalPage:1
    width: 800
    height: 391

    function getTitle(index)
    {
        switch(index)
        {
            case 0:
                return qsTr("日期")
            case 1:
                return qsTr("重量")
            case 2:
                return qsTr("模式")
            case 3:
                return qsTr("状态")
        }
    }

    Component.onCompleted:
    {
        signalRefresh();
        myTableModel.rows = Qt.binding(function() { return mymodbus.weightDatas })
    }
    Dialog {
        anchors.centerIn: parent
        id: exportOKDialog
        standardButtons: Dialog.Ok
        modal: true
        closePolicy: "CloseOnEscape"
        z:100
    }

    function exportData()
    {
        var result = mymodbus.exportToCsv(m_startTime, m_endTime)
        if(result)
        {
            exportOKDialog.title=qsTr("导出成功!")
            exportOKDialog.accepted.connect(function() {
                exportOKDialog.close()
            })
        }
        else
        {
            exportOKDialog.title=qsTr("导出失败，请检查是否接入U盘!")
            exportOKDialog.accepted.connect(function() {
                exportOKDialog.close()
            })
        }
        loaderText.visible =false
        exportOKDialog.open()
    }
    DateTimeDialog{
        id: dlg
        text: dateType==0?qsTr("开始日期"):qsTr("结束日期")
        //type: "Date"
        onAccepted: {
            if(dateType==0){
                startDate.text=getText("yyyy-MM-dd hh:mm:ss")
            }
            else{
                endDate.text=getText("yyyy-MM-dd hh:mm:ss")
            }
            if (typeof rectangle !== 'undefined' && typeof rectangle.resetScreenSaverTimer === 'function') {
                rectangle.resetScreenSaverTimer();
            }
        }
        onRejected: {
            // 取消时也复位屏幕保护定时器
            if (typeof rectangle !== 'undefined' && typeof rectangle.resetScreenSaverTimer === 'function') {
                rectangle.resetScreenSaverTimer();
            }
        }
    }

    Rectangle
    {
        width:800
        height: 50
        color:"transparent"
        GridLayout{ //root中放置一个行布局，布局中放置3个方块
            id: zeroCalibrationLayout
            anchors.fill: parent
            //columnSpacing: 20 //间距
            rows: 1//行数
            columns: 5 //列数
            Button
            {
                id:startDate
                Layout.row:0
                Layout.column:0
                Layout.preferredWidth: 210
                Layout.preferredHeight: btnHeight
                font.pixelSize: 15
                text:m_startTime
                background:
                Rectangle{
                    border.width: 0
                    color: "#7584C2"
                }
                onClicked: {
                    dateType=0
                    if (typeof rectangle !== 'undefined' && typeof rectangle.stopScreenSaverTimer === 'function') {
                        rectangle.stopScreenSaverTimer();
                    }  
                    dlg.open()
                    dlg.exec(startDate.text)
                }
                palette.buttonText: "white"
            }
            Text
            {
                Layout.row:0
                Layout.column:1
                Layout.preferredWidth: btnWidth
                Layout.preferredHeight: btnHeight
                text:qsTr("至")
                font.pixelSize: 25
                color: "white"
                verticalAlignment: Text.AlignVCenter
            }
            Button
            {
                id:endDate
                Layout.row:0
                Layout.column:2
                Layout.preferredWidth: 210
                Layout.preferredHeight: btnHeight
                font.pixelSize: 15
                text:m_endTime//.slice(0,10)
                    //Qt.formatDateTime(new Date(), "yyyy-MM-dd")
                background:Rectangle{
                    border.width: 0
                    color: "#7584C2"
                }
                palette.buttonText: "white"
                onClicked: {
                    dateType=1
                        if (typeof rectangle !== 'undefined' && typeof rectangle.stopScreenSaverTimer === 'function') {
                            rectangle.stopScreenSaverTimer();
                        }
                    dlg.open()
                    dlg.exec(endDate.text)
                }
            }
            Button
            {
                id:btnQuery
                Layout.row:0
                Layout.column:3
                Layout.preferredWidth: 120
                Layout.preferredHeight: 45
                background: Rectangle{
                    border.width: 0
                    color: "#C070B0"
                }
                palette.buttonText: "white"
                text: qsTr("查询")
                font.pixelSize: 25
                onClicked: {
                    if(dataLoader.visible){
                        return
                    }
                    if(loaderText.visible)
                    {
                        return;
                    }
                    dataLoader.visible = true
                    dataTimmer.start()
                    m_startTime=startDate.text//+" 00:00:00"
                    mymodbus.setStartTime(m_startTime);
                    m_endTime=endDate.text//+" 23:59:59"
                    mymodbus.setEndTime(m_endTime);
                    m_currentPage = 0
                    mymodbus.setCurrentPage(m_currentPage);
                    //MyTableModel.slotParaChanged(m_startTime,m_endTime,m_currentPage)
                    totalPage = mymodbus.totalCount(m_startTime,m_endTime)
                    pageNum.text=(m_currentPage+1)+"/"+(totalPage)
                }
            }
            Button
            {
                id:btnExport
                Layout.row:0
                Layout.column:4
                Layout.preferredWidth: 120
                Layout.preferredHeight: 45
                background: Rectangle{
                    border.width: 0
                    color: "#C070B0"
                        }
                palette.buttonText: "white"
                text: qsTr("导出")
                font.pixelSize: 25
                onClicked: {
                    if(dataLoader.visible){
                        return
                    }
                    if(loaderText.visible)
                    {
                        return;
                    }
                    loaderText.visible=true;
                    funcTimer.start();

                }
            }
        }
    }
    TableView {
        id: tableView
        columnWidthProvider: function (column) {
            return root.columnWidthArr[column];
        }
        rowHeightProvider: function (row) {
            return root.verHeaderHeight;
        }
        Layout.margins: 0
        anchors{
            top: parent.top
            topMargin: 50+root.horHeaderHeight
            bottom: parent.bottom
            bottomMargin: 43
            left: parent.left
            leftMargin: 0  // 比原来的0增加1像素，实现右移
            right: parent.right
            rightMargin: 0
        }
        model: TableModel
        {
            id:myTableModel
            TableModelColumn { display: "createdTime" }
            TableModelColumn { display: "strWeight" }
            TableModelColumn { display: "strScheduled" }
            TableModelColumn { display: "strMode" }
            //rows:{}
        }
        // 启用虚拟化
        reuseItems: true
        clip: true // 确保只绘制可见区域

        delegate: Item { // 避免使用Rectangle作为根元素
            width: tableView.columnWidthProvider(model.row)
            height: horHeaderHeight
            Rectangle { // 将背景移到内部
                anchors.fill: parent
                color:"#0A3653"
                border.color:"white"
            }
            Label {
                id: label
                text: display
                anchors.fill: parent
                anchors.margins: 0
                color: "white"
                font.pixelSize: 20
                verticalAlignment: Text.AlignVCenter
                horizontalAlignment: Text.AlignHCenter
                renderType: Text.NativeRendering // 启用原生渲染加速
            }
        }
        // 监听数据模型变化，避免不必要的布局
        onModelChanged: {
            // 仅在需要时进行布局
            if (contentWidth === 0 || contentHeight === 0) {
                forceLayout();
            }
        }
    }
    //定义横向表头
    Item{
        id: header_horizontal
        anchors{
            left: parent.left
            right: parent.right
            leftMargin: root.verHeaderWidth
            top: parent.top
            topMargin: 50
        }
        height: root.horHeaderHeight
        z: 2

        Row {
            id: header_horizontal_row
            anchors.fill: parent
            leftPadding: -tableView.contentX
            clip: true
            spacing: 0

            Repeater {
                model: [qsTr("日期"), qsTr("重量"), qsTr("模式"), qsTr("状态")]
                    //tableView.columns > 0 ? tableView.columns : 0

                Rectangle {
                    id: header_horizontal_item
                    width: tableView.columnWidthProvider(index)
                    height: root.horHeaderHeight
                    color: "#0A3653"
                    border.color:"white"

                    Text {
                        anchors.centerIn: parent
                        text: getTitle(index)
                        color: "white"
                    }
                }
            }
        }
    }
    Timer{
        id:dataTimmer
        interval: 200
        running: false
        repeat: false
        onTriggered: {dataLoader.visible = false}
    }
    Timer {
        id:funcTimer
                running: false
                repeat: false
                interval:100
                onTriggered: {
                    exportData()
                }
            }

    MyBuzyIndicator{
        anchors.centerIn: parent
        id: dataLoader
        visible:false
    }
    Rectangle{
        x: -1
        y: 330
        height:45
        width: 800
        color:"transparent"

        Row {
            anchors.centerIn: parent
            spacing: 10
            Button {
                id: btnFirstPage
                height: 40
                width: 123
                text: qsTr("首页")
                font.pixelSize: 25
                palette.buttonText: "white"
                onClicked: {
                    if(dataLoader.visible){
                        return
                    }
                    if(loaderText.visible)
                    {
                        return;
                    }
                    dataLoader.visible = true
                    dataTimmer.start()
                    m_startTime=startDate.text//+" 00:00:00"
                    mymodbus.setStartTime(m_startTime)
                    m_endTime=endDate.text//+" 23:59:59"
                    mymodbus.setEndTime(m_endTime)
                    m_currentPage = 0
                    mymodbus.setCurrentPage(m_currentPage);
                    pageNum.text=(m_currentPage+1)+"/"+(totalPage)
                    //tableView.forceLayout()
                }
                background: Rectangle {
                    color: "#7584c2"
                    border.width: 0
                }
            }
            Button {
                id: btnPrePage
                height: 40
                width: 123
                text: qsTr("上一页")
                font.pixelSize: 25
                palette.buttonText: "white"
                onClicked: {
                    if(dataLoader.visible){
                        return
                    }
                    if(loaderText.visible)
                    {
                        return;
                    }
                    dataLoader.visible = true
                    dataTimmer.start()
                    m_startTime=startDate.text//+" 00:00:00"
                    mymodbus.setStartTime(m_startTime)
                    m_endTime=endDate.text//+" 23:59:59"
                    mymodbus.setEndTime(m_endTime)
                    if(m_currentPage > 0)
                    {
                        m_currentPage = m_currentPage - 1;
                        mymodbus.setCurrentPage(m_currentPage);
                    }
                    pageNum.text=(m_currentPage+1)+"/"+(totalPage)
                    //tableView.forceLayout()
                }
                background: Rectangle {
                    color: "#7584c2"
                    border.width: 0
                }
            }
            Text{
                id:pageNum
                font.pixelSize: 38
                height:40
                color:"White"
                text:(m_currentPage+1)+"/"+(totalPage)
            }

            Button {
                id: btnNextPage
                height: 40
                width: 123
                text: qsTr("下一页")
                font.pixelSize: 25
                palette.buttonText: "white"
                onClicked: {
                    if(dataLoader.visible){
                        return
                    }
                    if(loaderText.visible)
                    {
                        return;
                    }
                    dataLoader.visible = true
                    dataTimmer.start()
                    m_startTime=startDate.text//+" 00:00:00"
                    mymodbus.setStartTime(m_startTime)
                    m_endTime=endDate.text//+" 23:59:59"
                    mymodbus.setEndTime(m_endTime)
                    if(m_currentPage<totalPage-1)
                    {
                        m_currentPage = m_currentPage + 1;
                        mymodbus.setCurrentPage(m_currentPage);
                    }
                    pageNum.text=(m_currentPage+1)+"/"+(totalPage)
                }
                background: Rectangle {
                    color: "#7584c2"
                    border.width: 0
                }
            }
            Button {
                id: btnLastPage
                height: 40
                width: 123
                text: qsTr("尾页")
                font.pixelSize: 25
                palette.buttonText: "white"
                onClicked: {
                    if(dataLoader.visible){
                        return
                    }
                    if(loaderText.visible)
                    {
                        return;
                    }
                    dataLoader.visible = true
                    dataTimmer.start()
                    m_startTime=startDate.text//+" 00:00:00"
                    mymodbus.setStartTime(m_startTime)
                    m_endTime=endDate.text//+" 23:59:59"
                    mymodbus.setEndTime(m_endTime)
                    m_currentPage = totalPage-1;
                    mymodbus.setCurrentPage(m_currentPage);
                    pageNum.text=(m_currentPage+1)+"/"+(totalPage)
                }
                background: Rectangle {
                    color: "#7584c2"
                    border.width: 0
                }
            }
        }
    }
    onSignalRefresh: {
        mymodbus.setStartTime(m_startTime);
        mymodbus.setEndTime(m_endTime);
        //mymodbus.setCurrentPage(-1);
        mymodbus.setCurrentPage(m_currentPage);
        totalPage = mymodbus.totalCount(m_startTime,m_endTime)
        pageNum.text=(m_currentPage+1).toString()+"/"+(totalPage).toString()
    }
}

